from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from django.views.generic import ListView, DeleteView
from django.views.decorators.http import require_http_methods
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseBadRequest, JsonResponse
from django.template.loader import render_to_string

from zanhu02.news.models import News
from zanhu02.helper import ajax_required,AuthorRequiredMixin

class NewListView(LoginRequiredMixin,ListView):
    """首页动态"""
    model = News
    paginate_by = 10 # 一页10条动态 ?page=
    context_object_name = 'news_list' # 模型类名_list 或者 object_list
    ordering = 'created_at'
    template_name = 'news/new_list.html' # 模型类名_list.html

    def get_queryset(self):
        return News.objects.filter(reply=False).select_related('user','parent').prefetch_related('liked')

@login_required
@ajax_required
@require_http_methods(['POST'])
def post_news(request):
    """ 发送动态, AJAX,POST请求"""
    post = request.POST['post'].strip()
    if post:
        posted = News.objects.create(user=request.user,content=post)
        html = render_to_string('news/news_single.html',{'news':posted,'request':request})
        return HttpResponse(html)
    else:
        return HttpResponseBadRequest('内容不能为空!')

class NewsDeleteView(LoginRequiredMixin,
                     AuthorRequiredMixin,DeleteView):
    # 这里要注意的两个问题
    # 登录的用户是不是动态的作者呢,是则删除,否则不能删除
    model = News
    template_name = 'news/news_confirm_delete.html'
    # slug_url_kwarg = 'slug' # 通过url传入要删除对象主键的id,默认值是slug
    pk_url_kwarg = 'pk'     # 通过url传入要删除对象主键的id,默认值是pk
    success_url = reverse_lazy('news:list')   # 在项目的URLconf未加载前使用


@login_required
@ajax_required
@require_http_methods(['POST'])
def like(request):
    """点赞,AJAX POST请求"""
    news_id = request.POST['news']
    news = News.objects.get(pk=news_id)
    # 取消或者添加赞
    news.switch_like(request.user)
    # 返回赞的数量
    return JsonResponse({'likes':news.count_likers()})

@login_required
@ajax_required
@require_http_methods(['GET'])
def get_thread(request):
    """ 返回动态的评论,AJAX,GET请求"""
    news_id = request.GET['news']
    news = News.objects.select_related('user').get(pk=news_id)
    news_html = render_to_string("news/news_single.html", {"news": news })  # 没有评论的时候
    thread_html = render_to_string("news/news_thread.html", {"thread": news.get_thread() })  #有评论的时候
    return JsonResponse({
        "uuid": news_id,
        "news": news_html,
        "thread": thread_html
    })

@login_required
@ajax_required
@require_http_methods(['POST'])
def post_comment(request):
    """ 评论,AJAX,POST请求"""
    post = request.POST['reply'].strip()
    parent_id = request.POST['parent']
    parent = News.objects.get(pk=parent_id)
    if post:
        parent.reply_this(request.user, post)
        return JsonResponse({'comments': parent.comment_count()})
    else:
        return HttpResponseBadRequest('内容不能为空!')


@login_required
@ajax_required
@require_http_methods(['POST'])
def update_interactions(request):
    """更新点赞数和评论数"""
    data_point = request.POST["id_value"]
    news = News.objects.get(pk=data_point)
    return JsonResponse({"likes":news.count_likers(),"comments":news.comment_count()})


